What is babel-plugin-transform-regenerator?
The babel-plugin-transform-regenerator npm package is used to transform ES2015+ generator functions into ES5 code. This is particularly useful for writing asynchronous code in a synchronous manner using the `yield` keyword, and for ensuring compatibility with older browsers or environments that do not support generator functions natively.
What are babel-plugin-transform-regenerator's main functionalities?
Transformation of generator functions
This feature allows developers to write generator functions using the `function*` syntax and `yield` keyword. The babel-plugin-transform-regenerator will then transform this into ES5 compatible code, enabling the use of generator functions in environments that do not support them natively.
function* gen() { yield 'Hello'; yield 'World'; }
Async/Await support
Although primarily focused on generator functions, babel-plugin-transform-regenerator also plays a crucial role in enabling the use of async/await syntax in projects that use Babel for transpilation. It transforms async functions into generator functions and then into ES5 code.
async function foo() { await bar(); }
Other packages similar to babel-plugin-transform-regenerator
@babel/plugin-transform-async-to-generator
This package transforms async functions into generator functions, similar to how babel-plugin-transform-regenerator handles async/await syntax. However, it is specifically focused on the async/await syntax rather than on generator functions in general.
regenerator-runtime
While not a Babel plugin, regenerator-runtime is often used in conjunction with babel-plugin-transform-regenerator to provide a runtime environment for the transformed generator functions. It includes a polyfill for the regenerator runtime, which is necessary for the transpiled generator functions to work.
babel-plugin-transform-regenerator
Transform async/generator functions with regenerator
Example
In
function* a() {
yield 1;
}
Out
var _marked = [a].map(regeneratorRuntime.mark);
function a() {
return regeneratorRuntime.wrap(function a$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return 1;
case 2:
case "end":
return _context.stop();
}
}
}, _marked[0], this);
}
Installation
npm install --save-dev babel-plugin-transform-regenerator
Usage
Via .babelrc
(Recommended)
Without options:
{
"plugins": ["transform-regenerator"]
}
With options:
name | default value |
---|
asyncGenerators | true |
generators | true |
async | true |
{
"plugins": [
["transform-regenerator", {
"asyncGenerators": false,
"generators": false,
"async": false
}]
]
}
Via CLI
babel --plugins transform-regenerator script.js
Via Node API
require("babel-core").transform("code", {
plugins: ["transform-regenerator"]
});